package com.dh.project.controller;

import com.dh.project.model.CustomerInfo;
import com.dh.project.other.ModelRes;
import com.dh.project.service.CustomerInfoService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.io.FileOutputStream;

/**
 * Created by admin on 2017/6/27.
 */
@Controller
public class testController {


    private CustomerInfoService customerInfoService;

    @Autowired
    public testController(CustomerInfoService customerInfoService){
        this.customerInfoService = customerInfoService;
    }

    @ResponseBody
    @RequestMapping(value = "daoChuExcel",produces = "text/html;charset=utf-8")
    public Object daoChuExcel(){

        Map map = new HashMap();
        List<CustomerInfo> customerInfos = customerInfoService.selectByMap(map);

        String excelName = System.currentTimeMillis() + ".xls";
        String result = "";
        //创建HSSFWorkbook对象
        HSSFWorkbook wb = new HSSFWorkbook();

        //创建HSSFSheet对象
        HSSFSheet sheet = wb.createSheet("F" + 1);
        for (int i = 0; i < customerInfos.size(); i++) {
            HSSFRow row = sheet.createRow(i);
            row.createCell(0).setCellValue(customerInfos.get(i).getCustomer_id());
            row.createCell(1).setCellValue(customerInfos.get(i).getCustomer_name());
            row.createCell(2).setCellValue(customerInfos.get(i).getCustomer_phone());
        }
        //输出Excel文件
        FileOutputStream output = null;
        try {
            output = new FileOutputStream("C:\\Users\\admin\\Desktop\\123\\" + excelName);
            wb.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return "导出失败！";
        }
        result = "file:///C:/Users/admin/Desktop/123/" + excelName;
        return new ModelRes(ModelRes.Status.SUCCESS,result);
    }
}
